/*
 * @(#)XmlUtils.java, 2009-2-22
 *
 * Copyright 2009 SuperV System Integration CO., LTD. All rights reserved.
 */
package org.lex.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 
 * 
 * @author Liu Er Xiao
 * @version 1.0, 2009-2-22
 */
public class XmlUtils {
	public static Document parseDocument(Reader in) throws DocumentException, IOException {
		return new SAXReader().read(new BufferedReader(in));
	}

	public static String formatXml(String xml) {
		try {
			return formatXml(DocumentHelper.parseText(xml));
		} catch (Exception e) {
			return xml;
		}
	}

	public static String formatXml(Node xml) {
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			StringWriter out = new StringWriter();
			XMLWriter writer = new XMLWriter(out, format);
			writer.write(xml);
			return out.toString();
		} catch (Exception e) {
			return xml.asXML();
		}
	}
}
